import { _decorator, assetManager, Component, ImageAsset, Label, Node, Prefab, Rect, Sprite, SpriteFrame, Texture2D, UITransform, v2, v3 } from 'cc';
import { BasicUI } from '../../Init/Basic/BasicUI';
import { UIExitAnimtions } from '../../Init/Tools/UIExitAnimations';
import { UISystem } from '../../Init/SystemUI/UISystem';
import { UIEnum } from '../../Init/SystemUI/UIEnum';
import { GlobalEnum } from '../../Init/Config/GlobalEnum';
import EventManager from '../../Init/Managers/EventManager';
import { EventTypes } from '../../Init/Managers/EventTypes';
import { CustomVerticalScrollView, ICustomScollViewData } from '../CommonScripts/CustomVerticalScrollView';
import { RankMgr } from '../../Init/SystemSDK/RankMgr';
import { StorageSystem } from '../../Init/SystemStorage/StorageSystem';
import { SDKSystem } from '../../Init/SystemSDK/SDKSystem';
import Loader from '../../Init/Tools/Loader';
import { GlobalTmpData } from '../../Init/Config/GlobalTmpData';
const { ccclass, property } = _decorator;

enum RankType {
    Country,
    Region
}

@ccclass('RankPopUI')
export class RankPopUI extends BasicUI {
    @property(Node)
    bg: Node = null;
    @property(Node)
    panel: Node = null;
    @property(Node)
    closeBtn: Node = null;

    @property(Prefab)
    rankItem: Prefab = null;

    protected onLoad(): void {
        this.initBtns();

    }

    protected onEnable(): void {
        this.enableBtns();
        this.enableItems();
    }

    protected start(): void {
        this.loadLocalIcon();
    }

    protected update(dt: number): void {
        this.updateSelfItems(dt);
        this.updateBtns(dt);
    }

    private showHideAnim() {
        this.bg.getComponent(UIExitAnimtions).showHideAnim(false);
        this.panel.getComponent(UIExitAnimtions).showHideAnim(false, () => {
            UISystem.hideUI(UIEnum.RankPopUI);
        }, true);
    }

    hideCb = null;
    isAnim = false;
    public show(d: { hideCb: any, isAnim: boolean }): void {
        super.show();
        this.hideCb = d && d.hideCb;
        this.isAnim = d && d.isAnim;

    }

    public hide(d?: any): void {
        super.hide(d);
        this.hideCb && this.hideCb();
        // 关闭时隐藏 授权按钮
        EventManager.emit(EventTypes.SDKEvents.HideRankAuthBtn);
    }

    //#region --- 地区按钮切换
    @property(Node)
    countryBtn: Node = null;
    @property(Node)
    regionBtn: Node = null;
    @property(Node)
    btnBg: Node = null;

    bgCurPos = v3();
    bgTarPos = v3();

    curRankType: RankType = RankType.Region;

    initBtns() {
        this.btnBg.active = true;
        this.bgCurPos.set(this.regionBtn.position);
        this.bgTarPos.set(this.regionBtn.position);
        this.btnBg.setPosition(this.bgCurPos);
    }
    enableBtns() {
        this.curRankType = RankType.Region;
        this.bgTarPos.set(this.regionBtn.position);
    }
    updateBtns(dt) {
        this.bgCurPos.lerp(this.bgTarPos, 0.2);
        this.btnBg.setPosition(this.bgCurPos);
    }
    onChangeToCountry() {
        this.bgTarPos.set(this.countryBtn.position);
        this.curRankType = RankType.Country;
        this.showRankItems();
    }

    onChangeToRegion() {
        this.bgTarPos.set(this.regionBtn.position);
        this.curRankType = RankType.Region;
        this.showRankItems();
    }

    //#endregion

    //#region --- 获取排行数据
    // 授权按钮位置- 与wx按钮重叠
    @property(Node)
    authBtn: Node = null;
    @property(Node)
    loadingTag: Node = null;

    @property(Label)
    cityLabel: Label = null;
    @property(Node)
    selfItem: Node = null;

    isAuth = false;
    // 更新频率
    updateDataCd = 30;
    preUpdateTime = 0;
    // 底部固定的自身信息
    userInfo: GlobalEnum.RankInfo;
    selfUid: string;
    // 自身信息
    selfItemData: RankPopItem;
    isSetSelfIcon = false;
    //
    countryRankData: RankPopItem[] = [];
    regionRankData: RankPopItem[] = [];

    @property(CustomVerticalScrollView)
    countryView: CustomVerticalScrollView = null;
    @property(CustomVerticalScrollView)
    regionView: CustomVerticalScrollView = null;

    initItems() {
        // 获取本地信息
        // const data = StorageSystem.getData();
        // const selfInfo = data.userAssets.selfInfo;
        // console.log('本地: selfInfo:', selfInfo);

        this.isAuth = false;
        this.selfUid = SDKSystem._sdkInfo.acount;
        this.loadingTag.active = true;
        this.userInfo = new GlobalEnum.RankInfo();

        let subStr = this.selfUid.substring(this.selfUid.length - 4, this.selfUid.length);
        //获取城市
        this.userInfo.city = SDKSystem.getCity();
        if (!this.userInfo.city) {
            EventManager.emit(EventTypes.SDKEvents.GetUserCity, (isSuccess, city) => {
                if (isSuccess) {
                    this.userInfo.city = city;
                    if (!this.isAuth) {
                        this.userInfo.nickName = (this.userInfo.city || '神秘') + '玩家' + subStr;
                    }
                    this.cityLabel.string = '地区: ' + (this.userInfo.city || '未知');
                }
            })
        }

        // 默认名称
        this.userInfo.nickName = (this.userInfo.city || '神秘') + '玩家' + subStr;

        // 默认 已自身id 作为自己的头像 url
        this.userInfo.avatarUrl = subStr;
        // 本地图片
        this.loadIcon(this.userInfo.avatarUrl, true);

        this.cityLabel.string = '地区: ' + (this.userInfo.city || '未知');
        console.log('userInfo:', this.userInfo);
    }

    enableItems() {
        if (!this.selfItemData) {
            this.initItems();
            // 初始数据
            let curLv = StorageSystem.getData().levelAssets.maxLv - 1;
            this.selfItemData = new RankPopItem(9999, this.selfUid, curLv, true, this.userInfo, this);
        }


        console.log('isAuth:', this.isAuth);
        this.showRankItems();

        if (!this.isAuth) {
            // 授权按钮 与 全国和地区按钮重叠
            this.showAuthBtn();
        }
    }
    // 展示排行信息
    showRankItems() {
        this.countryView.node.active = false;
        this.regionView.node.active = false;

        this.getRankData();
    }

    //#region -------- 授权 ----------
    // 显示授权按钮
    showAuthBtn() {
        // 1. 先检测是否授权->成功->直接获取用户数据 失败->授权按钮
        EventManager.emit(EventTypes.SDKEvents.CheckUserInfoAuth, (res) => {
            console.log('CheckUserInfoAuth:', res);

            if (!res) {
                // 2.创建授权按钮
                const _size = this.authBtn.getComponent(UITransform).contentSize;
                const pos = v2(this.authBtn.worldPosition.x, this.authBtn.worldPosition.y);
                const rect = new Rect(pos.x, pos.y, _size.width, _size.height);

                EventManager.emit(EventTypes.SDKEvents.GetUserInfo, rect, (res) => {
                    console.log('GetUserInfo:', res);
                    this.onAuthFinished(res);
                    //切换到全国
                    this.onChangeToCountry();
                });
            } else {
                this.onAuthFinished(res);
            }
        })
    }
    // 获取用户数据完成
    onAuthFinished(res) {
        if (res && res.userInfo) {
            // 授权成功
            this.userInfo.nickName = res.userInfo.nickName;
            this.userInfo.avatarUrl = res.userInfo.avatarUrl;
            //
            this.isAuth = true;
            // 加载自身头像
            this.loadIcon(this.userInfo.avatarUrl);
        } else {
            this.isAuth = false;
        }
    }
    //#endregion

    //#region -------- 获取数据 ----------
    // 获取排名数据
    getRankData() {
        console.log('获取排名数据');

        const maxLv = StorageSystem.getData().levelAssets.maxLv - 1;
        const curt = Date.now();
        if (this.countryRankData.length == 0 ||
            curt - this.preUpdateTime > this.updateDataCd * 1000) {
            this.preUpdateTime = curt;

            this.loadingTag.active = true;
            const maxLen = 99;
            // 上传数据
            RankMgr.inst.submitWorldScore(this.userInfo, maxLv, (res) => {
                console.log('上传数据结果', res);

                // 获取数据
                RankMgr.inst.getWorldRankData(null, maxLen, (res) => {
                    // this.rankData = res;
                    if (res.code == 200) {
                        // 重置
                        this.countryRankData.length = 0;
                        this.regionRankData.length = 0;

                        let hasSelf = false;
                        // info： json数据 :RankInfo格式
                        const arr: { info: string, score: number, uid: string }[] = res.data.data;
                        // 创建数据
                        for (let i = 0; i < arr.length; i++) {
                            const d = arr[i];
                            const isSelf = d.uid == this.selfUid;
                            // 全国
                            let info: GlobalEnum.RankInfo = this.userInfo;
                            if (!isSelf) {
                                info = JSON.parse(d.info);
                            } else {
                                hasSelf = true;
                            }

                            const item1 = new RankPopItem(
                                i,
                                d.uid,
                                d.score,
                                isSelf,
                                info,
                                this
                            );
                            this.countryRankData.push(item1);

                            // 地区
                            if (this.userInfo.city &&
                                info.city + '' == this.userInfo.city || isSelf) {
                                const item2 = new RankPopItem(
                                    i,
                                    d.uid,
                                    d.score,
                                    isSelf,
                                    info,
                                    this
                                );
                                this.regionRankData.push(item2);
                            }
                        }

                        // 未到上限时 将自身加入序列
                        if (!hasSelf) {

                            if (this.countryRankData.length < maxLen) {
                                const item3 = new RankPopItem(
                                    0,
                                    this.selfUid,
                                    maxLv,
                                    true,
                                    this.userInfo,
                                    this
                                );
                                this.countryRankData.push(item3);
                            }

                            if (this.regionRankData.length < maxLen) {
                                const item4 = new RankPopItem(
                                    0,
                                    this.selfUid,
                                    maxLv,
                                    true,
                                    this.userInfo,
                                    this
                                );
                                this.regionRankData.push(item4);
                            }
                        }

                    }
                    console.log('获取数据结果', res);
                    // console.log('排名数据', this.countryRankData, this.regionRankData);

                    this.refreshData();
                })
            })
        } else {
            // 刷新排名
            this.refreshData();
        }
    }
    // 刷新排名
    refreshData() {
        const maxLv = StorageSystem.getData().levelAssets.maxLv - 1;
        // 更新自己信息
        this.selfItemData.lv = maxLv;

        this.loadingTag.active = false;
        // 排序-更新排名
        this.countryRankData.sort((a, b) => {
            return b.lv - a.lv;
        });
        this.regionRankData.sort((a, b) => {
            return b.lv - a.lv;
        });
        let selfCountryRankIdx = 100;
        for (let i = 0; i < this.countryRankData.length; i++) {
            const e = this.countryRankData[i];
            e.idx = i + 1;
            if (e.uid == this.selfUid) {
                selfCountryRankIdx = e.idx;
            }
        }
        let selfRegionRankIdx = 100;
        for (let i = 0; i < this.regionRankData.length; i++) {
            const e = this.regionRankData[i];
            e.idx = i + 1;
            if (e.uid == this.selfUid) {
                selfRegionRankIdx = e.idx;
            }
        }
        // 更新底部自身排名
        this.selfItemData.idx = this.curRankType == RankType.Country ? selfCountryRankIdx : selfRegionRankIdx;

        this.countryView.initData(this.countryRankData, this.rankItem);
        this.regionView.initData(this.regionRankData, this.rankItem);

        this.countryView.node.active = this.curRankType == RankType.Country;
        this.regionView.node.active = this.curRankType == RankType.Region;

        this.setSelfInfo();

        // 滚到到自身位置
        // this.countryView.scorllToIdx(this.selfItemData.idx - 1);
        // this.regionView.scorllToIdx(this.selfItemData.idx - 1);

        // console.log('排名数据：', this.regionRankData);
    }
    // 更新设置自身头像
    updateSelfItems(dt: number) {
        if (!this.selfItemData) return;
        // 更新自身数据
        if (!this.isSetSelfIcon &&
            this.iconRecs[this.userInfo.avatarUrl] &&
            this.iconRecs[this.userInfo.avatarUrl].sf) {

            this.isSetSelfIcon = true;
            this.selfItem.getChildByName('icon').getComponent(Sprite).spriteFrame =
                this.iconRecs[this.userInfo.avatarUrl].sf;
        }

    }
    // 设置自身信息
    setSelfInfo() {
        if (!this.selfItemData) return;
        this.selfItem.active = true;

        let rankIdx = this.selfItemData.idx;
        let rankLabel = this.selfItem.getChildByName('rankLabel');
        rankLabel.getComponent(Label).string = rankIdx > 99 ? '99+' : rankIdx.toFixed(0);
        let top3 = this.selfItem.getChildByName('top3');
        top3.active = this.selfItemData.idx <= 3;
        rankLabel.active = this.selfItemData.idx >= 3;
        for (let i = 0; i < top3.children.length; i++) {
            top3.children[i].active = (this.selfItemData.idx - 1) == i;
        }
        //
        this.selfItem.getChildByName('scoreLabel').getComponent(Label).string = '第' + this.selfItemData.lv + '关';
        this.selfItem.getChildByName('nameLabel').getComponent(Label).string = this.selfItemData.info.nickName;
        //
        let selfBg = this.selfItem.getChildByName('selfBg');
        selfBg.active = true;
        //
        this.isSetSelfIcon = false;
    }
    //#endregion

    //#endregion

    //#region ---按钮
    onCloseClick() {
        this.showHideAnim();
    }
    onShareClick() {

        EventManager.emit(EventTypes.SDKEvents.Share, {
            title: '太好玩了,来一起挑战吧!', useUrl: true,
            urlType: this.isAnim ? GlobalEnum.SharePosition.WinPage : GlobalEnum.SharePosition.HomePage
        })
        EventManager.emit(EventTypes.SDKEvents.ShareReport, '排行榜分享');
    }
    //#endregion

    //#region ---加载icon
    // state: 0 未加载 1 加载完成 2 加载失败
    iconRecs: { [url: string]: { state: number, useLocal: boolean, sf: SpriteFrame } } = {};
    // http正则表达式
    httpRegex = /http/i;
    public loadIcon(url: string, useLocal = false) {
        if (typeof url != 'string') {
            console.warn('url必须是字符串');
            return;
        }

        // console.log("加载icon", url, useLocal);
        if (!this.iconRecs[url]) {
            // 修正错误url 验证是否包含http
            if (!this.httpRegex.test(url)) {
                useLocal = true;
            }
            this.iconRecs[url] = { state: 0, useLocal: useLocal, sf: null };

            if (useLocal) {
                // 随机本地图片
                this.iconRecs[url].state = 2;
                if (this.localIconArr.length > 0) {
                    this.getLocalIcon(url);
                }
                return;
            }

            // 加载图片
            assetManager.loadRemote(url, { ext: '.jpg' }, (err, res: ImageAsset) => {
                if (!err) {
                    res.addRef();
                    let tx = new Texture2D();
                    tx.image = res;
                    let sf = new SpriteFrame();
                    sf.texture = tx;
                    sf.packable = false;

                    this.iconRecs[url].sf = sf;
                    this.iconRecs[url].state = 1;

                } else {
                    // 加载失败->随机本地图片
                    this.iconRecs[url].state = 2;
                    // if (this.localIconArr.length > 0) {
                    //     this.iconRecs[url].state = 1;
                    //     this.iconRecs[url].sf = this.localIconArr[Math.floor(Math.random() * this.localIconArr.length)];
                    // }
                }
            })
        }
    }

    localIconArr: SpriteFrame[] = [];
    // 加载本地的
    private loadLocalIcon() {
        Loader.loadBundle('UI', () => {
            Loader.loadBundleDir('UI', 'Assets/Images/RankListUI/avatar', (arr: SpriteFrame[]) => {
                for (let i = 0; i < arr.length; i++) {
                    const e = arr[i];
                    this.localIconArr.push(e);
                    e.packable = false;
                }

                // 替换本地图片
                for (let url in this.iconRecs) {
                    if (this.iconRecs[url].useLocal) {
                        this.getLocalIcon(url);
                    }
                }

                console.log('本地图片加载完成', this.localIconArr.length);
            }, SpriteFrame);
        })
    }
    /** 取最后一位 */
    private getLocalIcon(str: string) {
        if (this.localIconArr.length > 0) {
            // 截取最后一个数字
            let idxStr = str[str.length - 1] || '1';
            let idx = parseInt(idxStr) || 1;
            // console.log('取本地图片', idx);
            if (this.localIconArr[idx]) {
                this.iconRecs[str].state = 1;
                this.iconRecs[str].sf = this.localIconArr[idx];
            }
        }
    }

    //#endregion
}

export class RankPopItem implements ICustomScollViewData {
    idx: number = 0;
    node: Node;
    info: GlobalEnum.RankInfo;

    uid: string;
    isSelf = false;

    isLoadIcon = false;
    iconRecs: { [url: string]: { state: number, sf: SpriteFrame } } = {};

    lv: number;
    rankPopUI: RankPopUI;

    //
    avatarUrl: string;

    constructor(idx: number, uid: string, lv: number, isSelf: boolean, info: GlobalEnum.RankInfo, rankPopUI: RankPopUI) {
        this.idx = idx;
        this.uid = uid;
        this.lv = lv;
        this.info = info;
        this.rankPopUI = rankPopUI;
        this.iconRecs = rankPopUI.iconRecs;
        this.isSelf = isSelf;
    }

    init(): void {
        //
        let rankLabel = this.node.getChildByName('rankLabel');
        rankLabel.getComponent(Label).string = (this.idx).toFixed(0);
        rankLabel.active = this.idx >= 3;
        let top3 = this.node.getChildByName('top3');
        top3.active = this.idx <= 3;
        for (let i = 0; i < top3.children.length; i++) {
            top3.children[i].active = (this.idx - 1) == i;
        }
        //
        this.node.getChildByName('scoreLabel').getComponent(Label).string = '第' + this.lv + '关';
        this.node.getChildByName('nameLabel').getComponent(Label).string = this.info.nickName;
        //
        let selfBg = this.node.getChildByName('selfBg');
        selfBg.active = this.isSelf;
        //
        this.isLoadIcon = false;
        if (this.info.avatarUrl) {
            this.avatarUrl = this.info.avatarUrl + '';
            this.rankPopUI.loadIcon(this.avatarUrl);
        } else {
            this.avatarUrl = this.info.nickName.substring(this.info.nickName.length - 4, this.info.nickName.length);
            this.rankPopUI.loadIcon(this.avatarUrl, true);
        }
        // console.log(this.info.nickName, '# avatarUrl', this.avatarUrl);
    }
    reset(): void {
        this.isLoadIcon = false;
    }
    update(dt): void {
        if (!this.isLoadIcon &&
            this.iconRecs[this.avatarUrl] &&
            this.iconRecs[this.avatarUrl].sf) {
            this.isLoadIcon = true;
            this.node.getChildByName('icon').getComponent(Sprite).spriteFrame = this.iconRecs[this.avatarUrl].sf;

        }
    }

}